//
//  AdressManageViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/10/1.
//  Copyright © 2016年 fatcat. All rights reserved.
//  收货地址管理

import UIKit

enum AddressManagerType {
    case Select
    case Edit
}

@objc protocol AddressReturnPreOrder {
    optional func setShownAdress(address: NSDictionary, atIndex: Int)
}

class AdressManageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    
    var delegate: AddressReturnPreOrder?
    var managerType: AddressManagerType! = .Select
    var currentSelected = 0
    
    var tableView: UITableView!
    
    var localAddress: NSMutableArray!
    
    var addBtn: UIButton!
    
    convenience init(managerType: AddressManagerType){
        self.init()
        self.managerType = managerType
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        localAddress = NSMutableArray()
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        // 新建按钮
        addBtn = UIButton(frame: CGRect(x: 0, y: view.bounds.height - 44, width: view.bounds.width, height: 44))
        addBtn.backgroundColor = UIColor.whiteColor()
        addBtn.setTitle("新建收货地址", forState: .Normal)
        addBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        view.addSubview(addBtn)
        addBtn.addTarget(self, action: #selector(AdressManageViewController.addAdress), forControlEvents: .TouchUpInside)
        
        if managerType == .Edit {
            
            
            title = "我的收货地址"
            let editBtn = UIBarButtonItem(title: "编辑", style: .Plain, target: self, action: #selector(AdressManageViewController.enterEditMode(_:)))
            navigationItem.rightBarButtonItem = editBtn
            
            let fakeNavBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
            view.addSubview(fakeNavBar)
            fakeNavBar.barTintColor = Fatcat.THEME_COLOR
            fakeNavBar.barStyle = .Black
            fakeNavBar.tintColor = UIColor.whiteColor()
            let fakeNavItem = UINavigationItem(title: title!)
            let fakeBackButton = UIBarButtonItem()
            fakeBackButton.title = "    返回"
            fakeNavItem.leftBarButtonItem = fakeBackButton
            fakeNavItem.rightBarButtonItem = editBtn
            fakeNavBar.pushNavigationItem(fakeNavItem, animated: false)
            
        }else{
            title = "选择收货地址"
        }
        
        let backItem = UIBarButtonItem()
        backItem.title = "返回"
        navigationItem.backBarButtonItem = backItem
        
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.navigationBar.hidden = false
        if NSFileManager.defaultManager().fileExistsAtPath("\(DOCUMENT_PATH)/address.plist") {
            localAddress = NSMutableArray(contentsOfFile: "\(DOCUMENT_PATH)/address.plist")
        }
        tableView.reloadData()
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            if localAddress.count == 0{
                return 0
            }
            return 1
        case 1:
            return localAddress.count-1
        default:
            return 1
        }
        
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return 80
        case 1:
            return 80
        default:
            return 44
        }
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 0:
            return "默认收货地址"
        default:
            return nil
        }
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 1{
            return 64
        }
        return 0
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "address")
        let addressLabel1 = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width-32, height: 16))
        cell.addSubview(addressLabel1)
        
        let addressLabel2 = UILabel(frame: CGRect(x: 16, y: 32, width: view.bounds.width-32, height: 16))
        cell.addSubview(addressLabel2)
        
        let addressLabel3 = UILabel(frame: CGRect(x: 16, y: 56, width: view.bounds.width-32, height: 16))
        cell.addSubview(addressLabel3)
        
        let thisRowInt = indexPath.section + indexPath.row
        
        let addressItem = localAddress.objectAtIndex(thisRowInt) as! NSDictionary
        addressLabel1.text = "\(addressItem.objectForKey("province") as! String) \(addressItem.objectForKey("city") as! String) \(addressItem.objectForKey("precinct") as! String)"
        addressLabel2.text = addressItem.objectForKey("specify") as? String
        addressLabel3.text = "\(addressItem.objectForKey("receiver") as! String) \(addressItem.objectForKey("phone") as! String)"
        
        if managerType == .Select {
            let thisRowInt = indexPath.row + indexPath.section
            if thisRowInt == currentSelected {
                cell.accessoryType = .Checkmark
            }
        }else{
            cell.accessoryType = .DisclosureIndicator
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let thisRowInt = indexPath.section + indexPath.row
        if managerType == .Edit{
            // TODO: 进入编辑
            hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(AdressAddViewController(addressIndex: thisRowInt), animated: true)
        }else{
            // MARK: 选择地址
            
            self.delegate?.setShownAdress?(localAddress.objectAtIndex(thisRowInt) as! NSDictionary, atIndex: thisRowInt)
            navigationController?.popViewControllerAnimated(true)
        }
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        if managerType == .Edit {
            return true
        }
        return false
    }
    
    func addAdress(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(AdressAddViewController(addressIndex: localAddress.count), animated: true)
    }
    
    func enterEditMode(sender:UIBarButtonItem) {
        if tableView.editing{
            sender.title = "编辑"
            tableView.editing = false
        }else{
            sender.title = "完成"
            tableView.editing = false
        }
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        localAddress.removeObjectAtIndex(indexPath.row)
        tableView.reloadData()
        localAddress.writeToFile("\(DOCUMENT_PATH)/address.plist", atomically: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
